package com.ibiz.test.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class DocXmlUtil {
	
	public static int DATA_DEACTION = 5 ;
	public static int DATA_DEFV = 6 ;
	
	public static int RESULT_DEACTION = 6 ;
	public static int RESULT_DEFV = 7 ;
	
	public static int DOC_ACTION = 1 ;
	
	private static Document doc = null ;
	
	
	public static Document getTestDoc() throws Exception {
		if(doc==null) {
			Map map = new HashMap();
			map.put("Workbook", "urn:schemas-microsoft-com:office:spreadsheet");
			SAXReader reader = new SAXReader();
			reader.getDocumentFactory().setXPathNamespaceURIs(map);
			Document doc = reader.read(DocXmlUtil.class.getClassLoader().getResourceAsStream("test.xml")) ;
			DocXmlUtil.doc = doc ;
			return doc ;
		}else {
			return DocXmlUtil.doc ;
		}
	}
	
	public static Node findTest(String testSn) throws Exception {
		String xpath = "//Workbook:Cell[Workbook:Data='"+testSn+"']/..";
		Node row = doc.selectSingleNode(xpath) ;
		
		return row ;
	}
	
	public static String findTestData(String testSn , int testDataType) throws Exception {
		String xpath = "//Workbook:Cell[Workbook:Data='"+testSn+"']/../Workbook:Cell["+testDataType+"]/Workbook:Data";
		Node data = doc.selectSingleNode(xpath) ;
		return data.getText() ;
	}
	
	public static void testSuccess(String testSn , int testResultType) throws Exception {
		String xpath = "//Workbook:Cell[Workbook:Data='"+testSn+"']/../Workbook:Cell["+testResultType+"]/Workbook:Data";
		Node testResult = doc.selectSingleNode(xpath) ;
		testResult.setText("通过");
	}
	
	public static void testFailure(String testSn , int testResultType) throws Exception {
		String xpath = "//Workbook:Cell[Workbook:Data='"+testSn+"']/../Workbook:Cell["+testResultType+"]/Workbook:Data";
		Node testResult = doc.selectSingleNode(xpath) ;
		testResult.setText("失败");
	}
	
	public static void saveXml() {
		try {
			String xpath = "//Workbook:Cell[Workbook:Data='"+"BXD002"+"']/../Workbook:Cell["+6+"]/Workbook:Data";
			Node testResult = doc.selectSingleNode(xpath) ;
			FileOutputStream out = new FileOutputStream("test-result.xml");
			XMLWriter writer = new XMLWriter(out) ;
			//写入数据
			writer.write(doc);
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

